package com.example.smartcity.ui;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.smartcity.R;
import com.example.smartcity.api.ApiService;
import com.example.smartcity.model.LoginResp;
import com.example.smartcity.utils.RetrofitHelper;
import com.example.smartcity.utils.SPUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        EditText etUsername = findViewById(R.id.et_username);
        EditText etPassword = findViewById(R.id.et_password);
        Button btnLogin = findViewById(R.id.btn_login);

        btnLogin.setOnClickListener(v -> {
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();

            RetrofitHelper.getService().login(username, password)
                    .enqueue(new Callback<LoginResp>() {
                        @Override
                        public void onResponse(Call<LoginResp> call, Response<LoginResp> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                SPUtils.putString("token", response.body().getToken());
                                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<LoginResp> call, Throwable t) {
                            Toast.makeText(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    });
        });
    }
}